﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Slam.FieldTypes;

namespace SlamCms.SharePoint.FieldTypes
{
	public class UneditableTextFieldControl : SlamFieldControl
	{
		protected TextBox txtField;
		protected Label lblText;

		protected override string DefaultTemplateName
		{
			get
			{
				return "SlamCMSUneditableTextFieldControl";
			}
		}

		//private bool isTitle;

		//public bool IsTitle
		//{
		//    get { return isTitle; }
		//    set { isTitle = value; }
		//}

		public override object Value
		{
			get
			{
				this.EnsureChildControls();

				return String.IsNullOrEmpty(txtField.Text) ? lblText.Text : txtField.Text;
			}
			set
			{
				this.EnsureChildControls();
				txtField.Text = value.ToString();
				lblText.Text = value.ToString();
			}
		}

		[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
		protected override void OnInit(EventArgs e)
		{
			base.CanCacheRenderedFieldValue = false;
			base.OnInit(e);
		}

		protected override void CreateChildControls()
		{
			if (Field == null)
				return;

			base.CreateChildControls();

			if (ControlMode == SPControlMode.Display)
				return;

			if (!base.IsFieldValueCached)
			{
				txtField = (TextBox)TemplateContainer.FindControl("txtField");
				lblText = (Label)TemplateContainer.FindControl("lblText");

				if (this.ItemFieldValue != null)
				{
					txtField.Text = this.ItemFieldValue.ToString();
					lblText.Text = this.ItemFieldValue.ToString();
				}

				bool userIsOwner = this.List.DoesUserHavePermissions(SPBasePermissions.ManageWeb);

				txtField.Visible = this.ItemFieldValue == null || userIsOwner;
				lblText.Visible = this.ItemFieldValue != null && !userIsOwner;
			}
		}
	}
}
